<template>
    <Popup ref="popupRef" :loading="loading" :formData="formData" :title="modeTitle" @submit="handleSubmit"
        @cancel="handleCancel" :rules="rules">
        <template #default="{ formData }">

            <a-form-item label="类型" field="type">
                <a-radio-group v-model="formData.type">
                    <a-radio :value="MenuType.CATALOGUE">目录</a-radio>
                    <a-radio :value="MenuType.MENU">菜单</a-radio>
                    <a-radio :value="MenuType.BUTTON">按钮</a-radio>
                </a-radio-group>
            </a-form-item>


            <a-form-item label="权限名称" field="name">
                <m-form-input v-model="formData.name" placeholder="请输入权限名称" />
            </a-form-item>

            <a-form-item label="父级" field="parent_id">
                <a-tree-select :fieldNames="{
                    key: 'id',
                    title: 'name',
                    children: 'children'
                }" v-model="formData.parent_id" :data="MenuTree" placeholder="请选择父级" />
            </a-form-item>

            <a-form-item label="路由名称" field="path" v-if="formData.type != MenuType.BUTTON">
                <m-form-input v-model="formData.path" placeholder="请输入路由名称" />
            </a-form-item>

            <a-form-item label="图标" field="icon" v-if="formData.type != MenuType.BUTTON">
                <m-form-icon-picker v-model="formData.icon" placeholder="请选择图标" />
            </a-form-item>

            <a-form-item label="权限地址" field="perms" v-if="formData.type !== MenuType.CATALOGUE">
                <m-form-input v-model="formData.perms" placeholder="请输入权限地址" />
                <template #extra>
                    <div>权限地址：如：/admin/system.user/list</div>
                    <div>对应后端地址: app/admin/controller/systen/userController/list</div>
                </template>
            </a-form-item>

            <a-form-item label="组件路径" field="component"
                v-if="formData.type === MenuType.MENU && formData.type != MenuType.BUTTON">
                <a-select allow-search allow-clear v-model="formData.component" :options="moduleOptions"
                    placeholder="请选择组件路径" />
                <template #extra>
                    <div>组件路径 建议先创建组件</div>

                </template>
            </a-form-item>

            <a-form-item label="是否隐藏" field="hidden" v-if="formData.type != MenuType.BUTTON">
                <a-switch v-model="formData.hidden" />
            </a-form-item>
            {{ formData }}
        </template>
    </Popup>
</template>

<script setup lang="ts">
import { filteredModules } from '@/utils/router'
import Popup from '@/components/Popup/index.vue'
import { MenuType } from '@/utils/enums/menuEnums'

import { getTreePermission, savePermission, updatePermission } from '@/api/system/auth/permission'
const popupRef = ref<InstanceType<typeof Popup>>()
const mode = ref<string | 'add' | 'edit'>('add')
const modeTitle = computed(() => {
    return mode.value === 'add' ? '新增' : '编辑'
})

const emits = defineEmits<{
    (e: 'success', data?: any): void
}>()

const moduleOptions = computed(() => {
    const rawModules = filteredModules();
    console.log(rawModules)
    return Object.entries(rawModules).map(([key]) => ({
        label: key,
        value: key
    }));
});


interface FormData {
    id?: number | null;
    path: string;
    type: number;
    parent_id: number;
    name: string;
    perms: string;
    component: string;
    hidden: boolean;
    icon: string;
}

const formData = reactive<FormData>({
    id: null,
    path: '',
    type: MenuType.CATALOGUE, // 设置默认值
    parent_id: 0,
    name: '',
    perms: '',
    component: '',
    hidden: false,
    icon: '',
})

const rules = {
    path: [
        { required: true, message: '请输入权限路由' }
    ],
    parent_id: [
        { required: true, message: '请选择父级' }
    ],
    type: [
        { required: true, message: '请选择类型' }
    ],
    name: [
        { required: true, message: '请输入权限名称' }
    ],
    perms: [
        { required: true, message: '请输入权限地址' }
    ],
    component: [
        { required: true, message: '请输入组件路径' }
    ]
}

const loading = ref(false)

const open = (type: string | 'add' | 'edit') => {
    mode.value = type
    // 重置表单数据到初始状态
    popupRef.value?.open()
    getMenuTreeData()
}
interface MenuTreeItem {
    id: number
    name: string
    children: MenuTreeItem[]
}

const MenuTree = ref<MenuTreeItem[]>([])
const getMenuTreeData = async () => {
    try {
        const res = await getTreePermission()
        // 处理数据，只保留需要的字段
        const processTreeData = (data: any[]): MenuTreeItem[] => {
            return data.map(item => ({
                id: item.id,
                name: item.name,
                children: item.children ? processTreeData(item.children) : []
            }))
        }

        // 添加一个根节点选项
        MenuTree.value = [
            {
                id: 0,
                name: '顶级菜单',
                children: processTreeData(res)
            }
        ]
    } catch (error) {
        console.error('获取菜单树失败:', error)
    }
}


const handleSubmit = async (data: FormData) => {
    try {
        loading.value = true
        mode.value === 'add' ? await savePermission(data) : await updatePermission(data)
        popupRef.value?.closeLoading()
        popupRef.value?.close()
        emits('success')

    } catch (error) {
        console.log(error)
        popupRef.value?.closeLoading()
    }
}


const setFormData = async (record: Record<any, any>) => {

    if (record) {
        // 使用解构赋值来合并数据
        const { children, ...rest } = record;

        for (const key in formData) {
            if (rest[key] != null && rest[key] != undefined) {
                //@ts-ignore
                formData[key] = rest[key]
            }
        }

        // Object.assign(formData, rest)
        // 确保弹窗组件也更新了数据
        nextTick(() => {
            popupRef.value?.setFormData(formData)
        })
    }

}

const handleCancel = () => {
    popupRef.value?.close()
}

defineExpose({
    open,
    setFormData
})
</script>
